﻿using jvm.classfile.constantpool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.classfile
{
    class ConstantPool
    {
        public ConstantInfo[] constantInfos;

        public void Read(ushort count, ClassReader reader)
        {
            // 这里千万注意了，常量池的索引没有0，从1开始，实际的count会大1个留给0的
            constantInfos = new ConstantInfo[count];
            for (int i = 1; i < count; i++)
            {
                ConstantInfo constantInfo = CPFactory.Create(reader);
                constantInfo.pool = this;
                constantInfo.Read(reader);
                constantInfos[i] = constantInfo;
                if (constantInfo.tag == (int)ConstantEnum.CONSTANT_Long ||
                    constantInfo.tag == (int)ConstantEnum.CONSTANT_Double)
                {
                    i++;
                }
            }
        }

        public string GetUtf8(ushort index)
        {
            ConstantUtf8Info utf8Info = (ConstantUtf8Info)constantInfos[index];
            return utf8Info.str;
        }

        public string GetClassName(ushort index)  {
            ConstantClassInfo classInfo = (ConstantClassInfo)constantInfos[index];
            return GetUtf8(classInfo.nameIndex);
        }

        public Tuple<string, string> GetNameAndType(ushort index)
        {
            ConstantNameAndTypeInfo nameAndTypeInfo = (ConstantNameAndTypeInfo)constantInfos[index];
            ushort nameIndex = nameAndTypeInfo.nameIndex;
            ushort descriptorIndex = nameAndTypeInfo.descriptorIndex;
            return new Tuple<string, string>(GetUtf8(nameIndex), GetUtf8(descriptorIndex));
        }
    }
}
